<template>
  <div class="dict-box">
    <a-row :class="['p-4']" :gutter="10">
      <a-col :xl="6" :lg="8" :md="10" :sm="24" style="flex: 1">
        <a-card :bordered="false" style="height: 100%">
          <a-button
            type="primary"
            :icon="h(PlusOutlined)"
            @click="addType"
            style="margin-bottom: 20px"
            v-auth="'dict:add'"
            >新增</a-button
          >
          <a-tree
            :tree-data="treeData.list"
            @select="changeSelect"
            :fieldNames="treeFieldnames"
            v-model:selectedKeys="selectedKeys"
            draggable
          >
            <template #title="{ key: treeKey, name, id }">
              <a-dropdown :trigger="['contextmenu']">
                <span>{{ name }} </span>
                <template #overlay>
                  <a-menu @click="({ key: menuKey }) => onContextMenuClick(treeKey, menuKey, id)">
                    <a-menu-item key="1" v-auth="'dict:edit'">编辑</a-menu-item>
                    <a-menu-item key="2" v-auth="'dict:delete'">删除</a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </template>
          </a-tree>
        </a-card>
      </a-col>
      <a-col :xl="18" :lg="16" :md="14" :sm="24" style="flex: 1">
        <a-card :bordered="false" style="height: 100%">
          <BasicTable @register="registerTable">
            <template #headerTop>
              <a-alert v-if="nowSelectName" :message="nowSelectName" type="info" />
            </template>

            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'action'">
                <TableAction
                  :actions="[
                    {
                      onClick: handleLook.bind(null, record),
                      label: '查看',
                    },
                    {
                      onClick: handleEdit.bind(null, record),
                      auth: 'dict:edit',
                      label: '编辑',
                    },
                    {
                      color: 'error',
                      onClick: handleDelete.bind(null, record),
                      auth: 'dict:delete',
                      label: '删除',
                    },
                  ]"
                />
              </template>
            </template>
          </BasicTable>
        </a-card>
      </a-col>
    </a-row>
    <a-modal
      v-model:visible="editTypeModel"
      :title="typeText[typeData.type] + '类型'"
      width="520"
      :footer-style="{ textAlign: 'right' }"
      @close="resetType"
    >
      <a-form :model="typeData.data" v-bind="layout" name="nest-messages" :disabled="formDisabled">
        <a-form-item label="父节点">
          <a-tree-select
            :fieldNames="fieldNames"
            v-model:value="typeData.data.parentId"
            show-search
            style="width: 100%"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            placeholder="请选择父节点"
            allow-clear
            :tree-data="treeDataSelect.list"
            tree-node-filter-prop="label"
          />
        </a-form-item>
        <a-form-item :name="['name']" label="类型名称">
          <a-input v-model:value="typeData.data.name" />
        </a-form-item>
        <a-form-item :name="['code']" label="类型编号">
          <a-input v-model:value="typeData.data.code" />
        </a-form-item>
        <a-form-item :name="['inputCode']" label="输入码">
          <a-input v-model:value="typeData.data.inputCode" />
        </a-form-item>
        <a-form-item :name="['iconUrl']" label="图标">
          <RwUpload
            :value="typeData.data.iconUrl"
            :base_url="base_url"
            :uploadUrl="uploadUrl"
            @change-valuie="changeEmit"
          />
        </a-form-item>
        <a-form-item :name="['isEnable']" label="是否启用">
          <a-switch v-model:checked="typeData.data.isEnable" />
        </a-form-item>
      </a-form>
      <template #footer>
        <a-button style="margin-right: 8px" @click="resetType"> 取消</a-button>
        <a-button type="primary" @click="saveType">确认</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { BasicTable, TableAction, useTable } from '@/components/Table';
  import { PlusOutlined } from '@ant-design/icons-vue';
  import { uploadUrl } from '@/api/common/api';
  import { columns } from './dict.data';
  import { list, listTypeApi, Type, allList, delInfo } from './dict.api';
  import { ITreeData, IResultTreeData } from './dict.type';
  import { ref, reactive, h, createVNode } from 'vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { Modal, message } from 'ant-design-vue';

  // import { SystemStore, ITemplate } from "@/store/modules/system";
  import RwUpload from '@/components/rw/upload.vue';
  import { useMessage } from '@/hooks/web/useMessage';
  // const system = SystemStore();
  const dictaddModel = ref<boolean>(false);
  const editTypeModel = ref<boolean>(false);
  const formDisabled = ref<boolean>(false);
  const selectedKeys = ref<string>('');
  const { createMessage: msg } = useMessage();
  const windowInstanse: any = window;
  const typeText = {
    look: '查看',
    edit: '编辑',
    add: '新增',
  };
  const layout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 18 },
  };
  const typeData: any = reactive({
    type: 'add',
    data: {
      isEnable: true,
    },
  });
  const base_url = ref<string>('');
  const selectId = ref<string>('');

  base_url.value = windowInstanse.config.base_url;
  const getList = () => {
    if (!selectId.value) return;
    reload({ parentId: selectId.value || '0', pageIndex: 1, pageSize: 10 });
  };

  const [registerTable, { reload }] = useTable({
    title: '',
    api: listTypeApi,
    columns,
    isTreeTable: false,
    pagination: true,
    striped: false,
    useSearchForm: false,
    showTableSetting: true,
    bordered: true,
    canResize: false,
    showIndexColumn: false,
    fetchSetting: {
      // 传给后台的当前页字段
      pageField: 'pageIndex',
      // 传给后台的每页显示多少条的字段
      sizeField: 'pageSize',
      // 接口返回表格数据的字段
      listField: 'data.entities',
      // 接口返回表格总数的字段
      totalField: 'data.totalCount',
    },
    searchInfo: {
      parentId: selectId,
    },
    actionColumn: {
      width: 120,
      title: '操作',
      dataIndex: 'action',
      // slots: { customRender: 'action' },
      fixed: 'right',
    },
  });
  const treeFieldnames = {
    children: 'children',
    title: 'name',
    key: 'id',
  };
  const fieldNames = {
    // tree-select
    children: 'children',
    label: 'name',
    value: 'id',
  };
  const nowSelectName = ref<string>('');

  const typeId = ref<string | number>('');
  const onContextMenuClick = (treeKey: string, menuKey: string, id) => {
    /** 右键菜单点击事件 */
    typeId.value = treeKey;
    // system.setTemplateId(typeId.value);

    switch (menuKey) {
      case '1':
        // 类型编辑
        editTypeModel.value = true;
        typeData.type = 'edit';
        typeData.data = SelectData;
        break;
      case '2':
        // 删除类型
        console.log(id, 'treeKey');
        dictaddModel.value = true;
        handleDelete({ id });
        break;
    }
  };

  // 获取树列表

  let treeData: any = reactive({ list: [] });
  let SelectData = reactive<ITreeData>([] as unknown as ITreeData);
  let treeDataSelect: any = reactive({ list: [] });
  const getTreeData = (): void => {
    list(0).then((res: IResultTreeData) => {
      try {
        treeData.list = res.data;
      } catch {}
    });
  };
  const getTreeDataAll = (): void => {
    allList(0).then((res: IResultTreeData) => {
      try {
        treeDataSelect.list = res.data;
        treeDataSelect.list.unshift({ name: '父节点', id: '0', value: '0', parentId: '0' });
      } catch {}
    });
  };
  const getTree = (): void => {
    getTreeData();
    getTreeDataAll();
  };
  // 监听树列表点击
  const changeSelect = (selectedKeys, e) => {
    // typeInfo(e.node.code).then((res: any) => {
    nowSelectName.value = e.node.name + ' ' + e.node.code;
    selectId.value = selectedKeys[0];
    SelectData = e.node.dataRef;
    // });
    getList();
  };

  getTree();

  const saveType = (): void => {
    // 保存类型
    Type[typeData.type](typeData.data).then((res: IResultTreeData) => {
      if (res.isSucceed) {
        msg.success(res.msg || '保存成功');
      } else {
        msg.error(res.msg || '保存失败');
      }
      resetType();
      getTree();
    });
  };
  const changeEmit = (e): void => {
    typeData.data.iconUrl = e;
  };
  const addType = (): void => {
    editTypeModel.value = true;
    formDisabled.value = false;
    typeData.type = 'add';
    typeData.data = {
      isEnable: true,
    };
    typeData.data.parentId = selectId.value;
  };
  const resetType = (): void => {
    editTypeModel.value = false;
    formDisabled.value = false;
    typeData.type = 'add';
    typeData.data = {};
    getList();
  };

  function handleLook(record) {
    editTypeModel.value = true;
    formDisabled.value = true;
    typeData.type = 'look';
    typeData.data = record;
  }

  function handleEdit(record) {
    editTypeModel.value = true;
    formDisabled.value = false;
    typeData.type = 'edit';
    typeData.data = record;
  }

  function handleDelete(record) {
    Modal.confirm({
      title: '确定删除?',
      icon: createVNode(ExclamationCircleOutlined),
      content: '数据字典数据为系统初始化数据，请谨慎删除！',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        if (record) {
          delInfo(record.id).then((res) => {
            if (res.isSucceed) {
              msg.success(res.msg || '删除成功');
            } else {
              msg.error(res.msg || '删除失败');
            }
            resetType();
            getTree();
          });
        }
      },
    });
    return false;
  }

  /**  处理添加模板成功逻辑 */
</script>

<style lang="less" scoped>
  .editFormBody {
    margin: 10px;
  }
</style>
